<template>
  <base-dialog
    ref="baseDialog"
    title="功能权限配置"
    @handleClose="handleClose"
    @handleSubmit="handleSubmit"
  >
    <el-row>
      <el-col :span="24">
        <el-tree
          ref="tree"
          :data="MenuData"
          show-checkbox
          node-key="id"
          :default-checked-keys="defKeys"
          :props="defaultProps"
        ></el-tree>
      </el-col>
    </el-row>
  </base-dialog>
</template>

<script>
import { getRoleFeatureById, setRoleFeature } from "@/api/system/role"
import { menuList } from "@/api/system/menu"
export default {
  data() {
    return {
      id: "",
      defKeys: [], // 默认选中的数组
      MenuData: [], //树结构
      defaultProps: {
        children: "children",
        label: "name"
      }
    }
  },
  methods: {
    async init(item) {
      this.$refs.baseDialog.dialogVisible = true
      if (item) {
        this.id = item.id
      }
      const res = await menuList()
      this.MenuData = res.data

      const { data } = await getRoleFeatureById(item.id)
      this.defKeys = this.resolveAllEunuchNodeId(this.MenuData, data, [])
    },
    handleClose() {
      this.id = ""
      this.defKeys = []
      this.MenuData = []
      this.$refs.baseDialog.dialogVisible = false
    },
    // 提交表单
    async handleSubmit() {
      const data = {
        roleId: this.id,
        menuIds: [...this.$refs.tree.getCheckedKeys(), ...this.$refs.tree.getHalfCheckedKeys()]
      }
      await setRoleFeature(data)
      this.$message.success("功能权限配置成功")
      this.handleClose()
    },
    /**
     * 解析出所有的太监节点id
     * @param json 待解析的json串
     * @param idArr 原始节点数组
     * @param temp 临时存放节点id的数组
     * @return 太监节点id数组
     */
    resolveAllEunuchNodeId(json, idArr, temp) {
      for (let i = 0; i < json.length; i++) {
        const item = json[i]
        // 存在子节点，递归遍历;不存在子节点，将json的id添加到临时数组中
        if (item.children && item.children.length !== 0) {
          this.resolveAllEunuchNodeId(item.children, idArr, temp)
        } else {
          temp.push(idArr.filter((id) => id === item.id))
        }
      }
      return temp
    }
  }
}
</script>

<style lang="scss" scoped>
.el-form {
  overflow: hidden;
  margin-bottom: 30px;
}
</style>
